const { sqlite3 } = require('../../mysql')

// 管理平台获取文章数据
const getArticle = async (ctx) => {
  // console.log('ctx.query:', ctx.query)
  let formData = ctx.query
  console.log('keyword:', formData.keyword)
  let offset = (formData.page - 1) * formData.limit
  let keyword = formData.keyword
  let limitdata = {}
  let data = {}
  if (keyword) {
    data = await sqlite3('article').where('title', 'LIKE', '%' + keyword + '%')
      .orderBy('id', 'desc').select().limit(formData.limit).offset(offset)
    total = data.length
  } else {
    // limitdata = await sqlite3('article').select()
    limitdata = await sqlite3('article').count({total: '*'})
    data = await sqlite3('article').orderBy('id', 'desc')
      .select().limit(formData.limit).offset(offset)
    total = limitdata[0].total
  }
  if (data) {
    // console.log('limitdata:', limitdata)
    ctx.body = {
      code: 200,
      item: data,
      total,
      result: true
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

const infoDelete = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('posts')
    .where('ID', formData.ID)
    .update('post_status', 'trash')
  console.log(data)
  if (data) {
    ctx.body = {
      code: 200,
      data: "success"
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

// 管理平台添加文章数据
const createContent = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('article').insert(formData)
  // console.log(data)
  if (data) {
    ctx.body = {
      code: 200,
      data: "success"
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

// 管理平台更新文章数据
const updateContent = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('article')
    .where('id', formData.id)
    .update(formData)
  // console.log(data)
  if (data) {
    ctx.body = {
      code: 200,
      data: "success"
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

module.exports = { getArticle, createContent, updateContent, infoDelete }
